using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using B.S.Medical.Domain.Medical;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using B.S.Medical.Api.Write.Application.Command.Register;

namespace B.S.Medical.Api.Write.Application.Handler.Register
{
    /// <summary>
    /// 修改挂号取消原因处理器
    /// </summary>
    public class UpdateRegisterCancelReasonHandler : IRequestHandler<UpdateRegisterCancelReasonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepository;
        private readonly ILogger<UpdateRegisterCancelReasonHandler> _logger;

        public UpdateRegisterCancelReasonHandler(
            IBaseRepository<RegisterModel> registerRepository,
            ILogger<UpdateRegisterCancelReasonHandler> logger)
        {
            _registerRepository = registerRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateRegisterCancelReasonCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询挂号记录
                var register = await _registerRepository.GetAll().FirstOrDefaultAsync(r => r.Id == request.Id, cancellationToken);
                if (register == null)
                {
                    return new ApiResult<int>
                    {
                        Data=0,
                        Code = ApiEnum.Fail,
                        Msg = "未找到该挂号记录"
                    };
                }

                // 更新取消原因
                register.RegisterRemark = request.RegisterRemark;
                
                // 保存更改
                await _registerRepository.UpdateAsync(register);

                return new  ApiResult<int>
                {
                    Data=1,
                    Code = ApiEnum.Success,
                    Msg = "取消原因修改成功"
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改挂号取消原因异常");
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = "修改异常：" + ex.Message
                };
            }
        }
    }
}